<template xmlns:background-color="http://www.w3.org/1999/xhtml">
  <a-row :gutter="10">
    <a-col :md="12" :sm="24" >
      <a-card :bordered="false">
        <!-- 按钮操作区域 -->
        <a-row style="margin-left: 14px">

          <a-button title="删除多条数据" @click="batchDel" type="default">批量删除</a-button>
          <span style='margin-left: 10px; color: blue'>蓝色表示区域</span>
          <!--<a-button @click="refresh" type="default" icon="reload" :loading="loading">刷新</a-button>-->
        </a-row>
        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <!-- 区域树-->
          <a-col :md="10" :sm="24">
            <template>
              <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
               <span style="user-select: none">
            <a-tree
              checkable
              v-model="checkedKeys"
              :loadedKeys="loadedKeys"
              :show-icon='true'
              @select="onSelect"
              @load="loadArea"
              @rightClick="rightHandle"
              :selected-keys="selectedKeys"
              :treeData="areaTree"
              :load-data="onLoadData"
              @expand="onExpand">
              <a-icon slot="project" type="project" />
               <a-icon slot="area" type="apartment" />
               <a-icon slot="build" type="hdd" />
               <a-icon slot="unit" type="cluster" />
               <a-icon slot="floor" type="table" />
               <a-icon slot="house" type="bank" />
              <template #title="item">
<!-- 项目黑色，区域蓝色，楼栋红色，单元紫色，楼层绿色                    -->
                <span v-if="item.isArea==0" style="color:black">项目：{{item.title}}</span>
                    <span v-if="item.isArea==1" style="color:blue">区域：{{item.title}}</span>
                    <span v-if="item.isArea==2" style="color:red">楼栋：{{item.title}}</span>
                    <span v-if="item.isArea==3" style="color:purple">单元：{{item.title}}</span>
                    <span v-if="item.isArea==4" style="color:green">楼层：{{item.title}}</span>
                    <span v-if="item.isArea==5" style="color:#000000">房屋：{{item.title}}</span>

              </template>
            </a-tree>
                </span>
                <!--新增右键点击事件,和增加添加和删除功能-->
                <a-menu  slot="overlay" >
                  <a-menu-item v-show='isArea||isProject' @click="bindProject" key="1">添加区域</a-menu-item>
                  <a-menu-item v-show='isArea' @click="objectAdd(1)" key="5">添加楼栋</a-menu-item>
                  <a-menu-item v-show='isBuild' @click="objectAdd(2)" key="6">添加单元</a-menu-item>
                  <a-menu-item v-show='isUnit' @click="objectAdd(3)" key="7">添加楼层</a-menu-item>
                  <a-menu-item v-show='isFloor' @click='objectAdd(4)' key='8'>添加房屋</a-menu-item>
                  <a-menu-item v-show='isArea||isBuild||isUnit||isFloor||isHouse' @click="changeName" key="4">重命名</a-menu-item>
                  <a-menu-item v-show='isArea||isBuild||isUnit||isFloor||isHouse' key="2">
                    <a-popconfirm title="确定删除吗?" @confirm="handleDelete">
                      <a>删除</a>
                    </a-popconfirm>
                    </a-menu-item>
                  <a-menu-item  @click="closeDrop" key="3">取消</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </a-col>
        </div>
      </a-card>
    </a-col>
    <area-modal ref="areaModal" @rightOk="rightOk"></area-modal>
    <select-project-modal ref="selectProjectModal" @ok="loadData"></select-project-modal>
    <add-modal-form ref='addModalForm' @ok='loadData'></add-modal-form>
  </a-row>
</template>
<script>
  import AreaModal from './modules/AreaModal'
  import AddModalForm from '@views/passage/project/modules/AddModalForm'
  import pick from 'lodash.pick'
  import {queryAreaTreeList, searchByKeywordsArea, deleteByDepartId} from '@/api/api'
  import { httpAction, deleteAction, postAction, getAction } from '@/api/manage'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import SelectProjectModal from '@views/system/modules/SelectProjectModal'
  // 表头
  const columns = [
    {
      title: '机构名称',
      dataIndex: 'departName'
    },
    {
      title: '机构类型',
      align: 'center',
      dataIndex: 'orgType'
    },
    {
      title: '机构编码',
      dataIndex: 'orgCode',
    },
    {
      title: '手机号',
      dataIndex: 'mobile'
    },
    {
      title: '传真',
      dataIndex: 'fax'
    },
    {
      title: '地址',
      dataIndex: 'address'
    },
    {
      title: '排序',
      align: 'center',
      dataIndex: 'departOrder'
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'action',
      scopedSlots: {customRender: 'action'}
    }
  ]
  export default {
    name: 'areTree',
    mixins: [JeecgListMixin],
    components: {
      SelectProjectModal,
      AreaModal,
      AddModalForm,
    },
    data() {
      return {
        treeKey:"",
        checkedKeys:[],
        loadedKeys: [],
        isProject:false,
        isArea:false,
        isBuild:false,
        isUnit:false,
        isFloor:false,
        loading: false,
        buildingId:"",
        areaId:"",
        projectId:"",
        unitId:"",
        floorId:"",
        autoExpandParent: true,
        currFlowId: '',
        currFlowName: '',
        isHouse:false,
        disable: true,
        visible: false,
        areaTree: [],
        rightClickNode:{},
        model: {},
        dropTrigger: '',
        depart: {},
        columns: columns,
        disableSubmit: false,
        currentProjectId:'',
        selectedKeys: [],
        houseId:'',
        autoIncr: 1,
        currSelected: {},
        form: this.$form.createForm(this),
        labelCol: {
          xs: {span: 24},
          sm: {span: 5}
        },
        node:{},
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        },
        graphDatasource: {
          nodes: [],
          edges: []
        },
        validatorRules: {
            name: {rules: [{required: true, message: '请输入区域名称!'}]},

        },
        url: {
          getAreaTree:'/project/getAreaTree',
          deleteArea: '/area/delete',
          deleteBuild:'/building/delete',
          deleteUnit:'/unit/delete',
          deleteFloor:'/floor/delete',
          deleteHouse:'/house/delHouse',
          edit: '/area/updateById',
          deleteBatch: '/area/deleteBatch',
          exportXlsUrl: "area/exportXls",
          importExcelUrl: "/area/importExcel",
          getAreaChildren: '/project/getChildren',
          getBuildChildren: '/area/getChildren',
          getUnitChildren: '/building/getChildren',
          getFloorChildren: '/unit/getChildren',
          getHouseChildren: '/floor/getChildren',
        },
        rightClickSelect:{},
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      loadArea(loadedKeys){
        this.loadedKeys = loadedKeys
      },
      loadData(node) {
        if (node!=undefined) {
          this.onLoadData(node)
        }
        if(this.node.value!=null){
          this.loadedKeys=[]
          this.onLoadData(this.node)
        }
      },
      rightOk(name){
        this.rightClickNode.title=name
        // this.onLoadData(this.node.$parent)
      },

      loadTree() {
        this.areaTree = []
        getAction(this.url.getAreaTree).then((res) => {
          if (res.success&&res.result!=null) {
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              this.areaTree.push(temp)
            }
            this.loading = false
          }
        })
      },
      onLoadData(treeNode) {
        return new Promise((resolve) => {
          setTimeout(() => {
            if (treeNode.dataRef.isArea!=null&&treeNode.dataRef.isArea!=5){
              let url = ''
              /*标识区域*/
              if (treeNode.dataRef.isArea==0) {
                url = this.url.getAreaChildren
              }else if(treeNode.dataRef.isArea==1){
                url = this.url.getBuildChildren
              }else if (treeNode.dataRef.isArea==2){
                url = this.url.getUnitChildren
              }else if (treeNode.dataRef.isArea==3){
                url = this.url.getFloorChildren
              }else if (treeNode.dataRef.isArea==4){
                url = this.url.getHouseChildren
              }
              getAction(url,{id:treeNode.dataRef.key}).then((res)=>{
                if (res.success&&res.result!=null){
                  treeNode.dataRef.children = res.result
                }
              })
            }
            this.areaTree = [...this.areaTree];
            resolve();
          }, 100);
        });
      },
      setThisExpandedKeys(node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      refresh() {
        this.loading = true
        this.loadTree()
      },
      getParent(node,locatName){
        let parentNode = node.$parent
        if(parentNode==null||parentNode==undefined||parentNode.dataRef==undefined||parentNode.dataRef==null)
        {
          return locatName;
        }
        if (parentNode.dataRef.isArea==0){
          this.projectId = parentNode.dataRef.id
        }
        locatName = parentNode.dataRef.title +'-'+ locatName
        return this.getParent(parentNode,locatName);
      },
      // 右键操作方法
      rightHandle(node) {
        this.node={}
        this.dropTrigger = 'contextmenu'
        if(node.node.dataRef.isArea === 0){
          this.resetRight();
          this.isProject=true
        }else if (node.node.dataRef.isArea === 1){
          this.resetRight();
          this.isArea = true
          this.areaId =  node.node.dataRef.id
        }else if (node.node.dataRef.isArea === 2){
          this.resetRight();
          this.isBuild = true
          this.buildingId =  node.node.dataRef.id
        }else if (node.node.dataRef.isArea === 3){
          this.resetRight();
          this.resetRight();
          this.unitId = node.node.dataRef.id
          this.isUnit = true
        }else if (node.node.dataRef.isArea === 4){
          this.resetRight();
          this.floorId = node.node.dataRef.id
          this.isFloor = true
        }else if (node.node.dataRef.isArea===5){
          this.resetRight()
          this.houseId=node.node.dataRef.id
          this.isHouse=true
        }
        this.node = node.node
        this.rightClickNode = node.node.dataRef
      },
      /*右键删除方法*/
      handleDelete() {
        let that = this
        let url = ''
        if (this.isArea) {
         url = this.url.deleteArea
        }else if(this.isBuild){
          url = this.url.deleteBuild
        }else if(this.isUnit){
          url = this.url.deleteUnit
        }else if(this.isFloor){
          url = this.url.deleteFloor
        }else if(this.isHouse){
          url = this.url.deleteHouse
        }
        deleteAction(url, { id: this.rightClickNode.key }).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData(that.node.$parent)
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      /*遍历树形集合，并获取到相应id的节点*/
      getTreeNode(areaTree,checkedKeys,checkedNode){

        if (areaTree.length<=0||checkedKeys.length<=0){
          return
        }
        for (let i = 0; i <areaTree.length; i++) {
          for (let j = 0; j <checkedKeys.length; j++) {
            if (areaTree[i].key===checkedKeys[j]){
              if(!checkedNode.includes(areaTree[i])){
                checkedNode.push(areaTree[i])
              }
            }
          }
          if (areaTree[i].children!=null&&areaTree[i].children.length!=0){
            this.getTreeNode(areaTree[i].children,checkedKeys,checkedNode)
          }
        }
      },
      getDelTreeNode(areaTree,checkedKeys,checkedNode){

        if (areaTree.length<=0||checkedKeys.length<=0){
          return
        }
        for (let i = 0; i <areaTree.length; i++) {
          for (let j = 0; j <checkedKeys.length; j++) {
            if (areaTree[i].key===checkedKeys[j]){
              let delElement={}
              delElement.id = areaTree[i].key
              delElement.isArea = areaTree[i].isArea
              delElement.title = areaTree[i].title
              checkedNode.push(delElement)
            }
          }
          if (areaTree[i].children!=null&&areaTree[i].children.length!=0){
            this.getDelTreeNode(areaTree[i].children,checkedKeys,checkedNode)
          }
        }
      },
      batchDel: function () {
        let that = this
        let checkedNode=[]
        this.getDelTreeNode(this.areaTree,this.checkedKeys,checkedNode)
        let delNum = 0
        for (let i = 0; i < checkedNode.length; i++) {
          if (checkedNode[i].isArea!=0){
            delNum++
          }
        }
        if (delNum <= 0) {
          this.$message.warning('请选择除项目外至少一条记录！')
        } else {
          this.$confirm({
            title: '确认删除',
            content: '确定要删除所选中的 ' + delNum + ' 条数据（项目不会删除）?',
            onOk: function () {
              httpAction(that.url.deleteBatch,checkedNode,'post').then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.refresh()
                  that.loadedKeys=[]
                  console.log(that.areaTree)
                  // that.onLoadData(that.node)
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
            }
          })
        }
      },

      bindProject(){
        this.$refs.selectProjectModal.setAreaId(this.rightClickNode)
        this.$refs.selectProjectModal.formVisible = true
        this.$refs.selectProjectModal.title = '添加项目区域'
      },
      objectAdd(num){
        let id = ""
        if (num==1){
          this.$refs.addModalForm.title="新增楼栋"
          id=this.areaId
        }else if(num==2){
          this.$refs.addModalForm.title="新增单元"
          id=this.buildingId
        }else if (num==3){
          this.$refs.addModalForm.title="新增楼层"
          id=this.unitId
        }else if(num==4){
          this.$refs.addModalForm.title='新增房屋'
          id = this.floorId
          let locateName=''
           locateName =  this.getParent(this.node,locateName)
          this.$refs.addModalForm.setHouse(id,this.projectId,locateName)
        }
        if (id!=""&&id!=null){
          if (num!=4){
            this.$refs.addModalForm.setId(id,num)
            this.$refs.addModalForm.disableSubmit = false;
          }
        }else{
          this.$message.warn("请先选择上级")
        }
      },
      resetRight(){
        this.isProject=false
          this.isArea=false
          this.isBuild=false
          this.isUnit=false
          this.isFloor=false
        this.isHouse=false
      },
      onExpand(expandedKeys) {
        this.loadedKeys=[]
        this.iExpandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      // 右键点击下拉框改变事件
      dropStatus(visible) {
        if (visible == false) {
          this.dropTrigger = ''
        }
      },
      // 右键店家下拉关闭下拉框
      closeDrop() {
        this.dropTrigger = ''
      },
      onSelect(selectedKeys, e) {
        let record = e.node.dataRef
        this.currSelected = Object.assign({}, record)
        this.model = this.currSelected
        this.selectedKeys = [record.key]
        this.model.parentId = record.parentId
        this.setValuesToForm(record)
      },
      // 触发onSelect事件时,为区域树右侧的form表单赋值
      setValuesToForm(record) {
        this.form.getFieldDecorator('fax', {initialValue: ''})
        this.form.setFieldsValue(pick(record, 'name', 'sort', 'status', 'remark'))
      },
      onClearSelected() {
        this.checkedKeys = []
        this.currSelected = {}
        this.form.resetFields()
        this.selectedKeys = []
      },
      changeName(){
          this.$refs.areaModal.changeAreaName(this.rightClickNode)
      },

      getFlowGraphData(node) {
        this.graphDatasource.nodes.push({
          id: node.id,
          text: node.flowNodeName
        })
        if (node.children.length > 0) {
          for (let a = 0; a < node.children.length; a++) {
            let temp = node.children[a]
            this.graphDatasource.edges.push({
              source: node.id,
              target: temp.id
            })
            this.getFlowGraphData(temp)
          }
        }
      },
    },
    created() {
      this.loadTree()
    },

  }
</script>
<style scoped>
  .ant-card-body .table-operator {
    margin: 15px;
  }

  .anty-form-btn {
    width: 100%;
    text-align: center;
  }

  .anty-form-btn button {
    margin: 0 5px;
  }

  .anty-node-layout .ant-layout-header {
    padding-right: 0
  }

  .header {
    padding: 0 8px;
  }

  .header button {
    margin: 0 3px
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  #app .desktop {
    height: auto !important;
  }

  /** Button按钮间距 */
  .ant-btn {
    margin-left: 3px
  }
</style>